package me.firstapp.api.bbs;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;

import me.firstapp.api.base.BaseApi;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.JsonPage;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.module.bbs.Topic;
import me.firstapp.service.bbs.TopicService;

@Controller
@RequestMapping(value = "/topic")
@Api(value = "/topic", description = "话题相关接口")
public class TopicApi extends BaseApi {

	@Autowired
	private TopicService topicService;

	@Autowired
	protected RedisTemplate<String, Object> redisTemplate;

	@RequestMapping(value = "/addTopic.do", method = RequestMethod.POST)
	@ApiOperation(value = "创建话题", notes = "创建话题")
	public void addTopic(@RequestBody Map<String, Object> body, Long memberId, Long sectionId,
			HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Topic> resultJsonObject = new SingleObject<Topic>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			String title = (String) body.get("title");
			String summary = (String) body.get("summary");
			String content = (String) body.get("content");

			Topic topic = topicService.addTopic(memberId, sectionId, title, summary, content, apiClientId);
			resultJsonObject.setObject(topic);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	@RequestMapping(value = "/findTopics.do", method = RequestMethod.GET)
	@ApiOperation(value = "分页查询话题", notes = "分页查询话题")
	public void findTopics(@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "20") Integer pageSize, Long sectionId,
			Long memberId, Integer recommend, String sortParam, String sortType, HttpServletRequest request,
			HttpServletResponse response) {
		PageObject<Topic> resultJsonPage = new PageObject<Topic>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Page<Topic> topicPage = topicService.findTopicsPage(pageNo, pageSize, sectionId, memberId, recommend,
					sortParam, sortType, apiClientId);
			JsonPage<Topic> jsonPage = new JsonPage<Topic>();
			jsonPage.setList(topicPage.getEntities());
			jsonPage.setPageNo(topicPage.getPageNo());
			jsonPage.setPageSize(topicPage.getPageSize());
			jsonPage.setTotalCount(topicPage.getEntityCount());
			resultJsonPage.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			resultJsonPage.setPage(jsonPage);
		} catch (ServiceException e) {
			resultJsonPage.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonPage.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonPage);
	}

	@RequestMapping(value = "findTopicsPageByParams.do", method = RequestMethod.POST)
	@ApiOperation(value = "分页查询话题", notes = "分页查询话题")
	public void findTopicsPageByParams(@RequestBody Map<String, Object> searchParams,
			@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "20") Integer pageSize, String sortParam,
			String sortType, Long startTime, Long endTime, HttpServletRequest request, HttpServletResponse response) {
		PageObject<Topic> resultJsonPage = new PageObject<Topic>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Date startDate = null;
			if (startTime != null) {
				startDate = DateUtils.getDateFromTimeStamp(String.valueOf(startTime), "yyyy-MM-dd");
			}
			Date endDate = null;
			if (endTime != null) {
				endDate = DateUtils.getDateFromTimeStamp(String.valueOf(endTime), "yyyy-MM-dd");
			}

			Page<Topic> topicPage = topicService.findTopicsPageByParams(pageNo, pageSize, searchParams, sortParam,
					sortType, startDate, endDate, apiClientId);
			JsonPage<Topic> jsonPage = new JsonPage<Topic>();
			jsonPage.setList(topicPage.getEntities());
			jsonPage.setPageNo(topicPage.getPageNo());
			jsonPage.setPageSize(topicPage.getPageSize());
			jsonPage.setTotalCount(topicPage.getEntityCount());
			resultJsonPage.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			resultJsonPage.setPage(jsonPage);
		} catch (ServiceException e) {
			resultJsonPage.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonPage.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonPage);
	}

	@RequestMapping(value = "/findTopicDetail.do", method = RequestMethod.GET)
	@ApiOperation(value = "查询话题详情", notes = "查询话题详情")
	public void findTopicDetail(Long topicId, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Topic> resultJsonObject = new SingleObject<Topic>();
		Long apiClientId = (Long) request.getAttribute("apiClientId");
		try {
			Topic topic = topicService.findTopicById(topicId, apiClientId);
			resultJsonObject.setObject(topic);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);

		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);

		// 记录浏览量
		@SuppressWarnings("unchecked")
		Map<Long, Long> topicViewCountsMap = (Map<Long, Long>) redisTemplate.opsForValue()
				.get("topicViewCountsMap" + apiClientId);
		if (topicViewCountsMap == null) {
			topicViewCountsMap = new HashMap<>();
		}
		Long counts = topicViewCountsMap.get(topicId);
		if (counts == null) {
			counts = 1L;
		} else {
			counts++;
		}
		topicViewCountsMap.put(topicId, counts);
		redisTemplate.opsForValue().set("topicViewCountsMap" + apiClientId, topicViewCountsMap);
	}

	@RequestMapping(value = "findMemberTopicsCounts.do", method = RequestMethod.GET)
	@ApiOperation(value = "获取用户話題量", notes = "获取用户話題量")
	public void findMemberTopicsCounts(Long memberId, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> resultJsonObject = new SingleObject<Object>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Long counts = topicService.findTopicsCountsByMemberId(memberId, apiClientId);
			resultJsonObject.setObject(counts);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	@RequestMapping(value = "findSomeTopics.do", method = RequestMethod.GET)
	@ApiOperation(value = "获取一定数量的話題", notes = "获取一定数量的話題")
	public void findSomeTopics(Long memberId, Long sectionId, Integer counts, HttpServletRequest request,
			HttpServletResponse response) {
		ListObject<Topic> listResult = new ListObject<>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			List<Topic> topics = topicService.findSomeTopics(memberId, sectionId, counts, apiClientId);
			listResult.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			listResult.setItems(topics);
		} catch (ServiceException e) {
			listResult.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			listResult.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, listResult);
	}

	@RequestMapping(value = "/deleteTopics.do", method = RequestMethod.POST)
	@ApiOperation(value = "删除話題", notes = "删除話題")
	public void deleteTopics(String topicIds, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			topicService.deleteTopics(topicIds, apiClientId);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/updateTopic.do", method = RequestMethod.POST)
	@ApiOperation(value = "更新話題", notes = "更新話題")
	public void updateTopic(@RequestBody Map<String, Object> body, Long topicId, Long upCounts, Long viewCounts,
			Long replyCounts, Long collectCounts, Integer recommend, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			String summary = (String) body.get("summary");
			String content = (String) body.get("content");
			Topic topic = topicService.updateTopic(topicId, summary, content, upCounts, viewCounts, replyCounts,
					collectCounts, recommend, apiClientId);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setObject(topic);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}
}
